from api import models
from api.extension.auth import UserAnonTokenAuthentication
from api.extension.filter import SelfFilterBackend
from api.extension.mixins import DigListModelMixin, DigCreateModelMixin
from api.extension.throttle import NewsCreateRateThrottle
from api.serializers.news import NewsSerializer, IndexSerializer
from django_filters import FilterSet, NumberFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.viewsets import GenericViewSet


class NewsFilterSet(FilterSet):
    latest_id = NumberFilter(field_name='id', lookup_expr='lt')

    class Meta:
        model = models.News
        fields = ['latest_id']


class NewsView(DigListModelMixin, DigCreateModelMixin, GenericViewSet):
    filter_backends = [SelfFilterBackend, DjangoFilterBackend]
    filterset_class = NewsFilterSet

    # 筛选当前用户未删除的资讯
    queryset = models.News.objects.filter(deleted=False).order_by('-id')
    serializer_class = NewsSerializer

    # 自定义类变量，限流
    throttle_objects = [NewsCreateRateThrottle(), ]

    def perform_create(self, serializer):
        # 需求：创建资讯时，默认对自己的内容做推荐。1.推荐数量+1 2.推荐记录+用户&资讯。在序列化类中实现
        serializer.save(user=self.request.user)
        # 数据库成功写入后，刷新限流记录
        for throttle in self.get_throttles():
            throttle.done()

    def get_throttles(self):
        if self.request.method == 'POST':
            return self.throttle_objects
        return []


class IndexFilterSet(FilterSet):
    latest_id = NumberFilter(field_name='id', lookup_expr='lt')

    class Meta:
        model = models.News
        fields = ['latest_id', 'zone']


class IndexView(DigListModelMixin, GenericViewSet):
    filter_backends = [DjangoFilterBackend]
    filterset_class = IndexFilterSet

    authentication_classes = [UserAnonTokenAuthentication]

    queryset = models.News.objects.filter(deleted=False).order_by('-id')
    serializer_class = IndexSerializer
